import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index.js'

import Layout from '@v/layout/Index'

import { getStorage } from '@/utils/localStorage.js'

Vue.use(Router)

// 基础路由
const routes = [
  {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: 'main',
    meta: { title: '', icon: '' },
    children: [
      { path: 'main', name: 'main', component: () => import('@v/main/Index.vue') }
    ]
  },
  {
    path: '/login', name: 'login', component: () => import('@v/login/Index.vue')
  }
]

// 错误页面路由
const routesError = [
  { path: '*', name: '404', component: () => import('@v/error/404.vue') }
]

const router = new Router({
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 登录页直接放行
  let path = to.path
  let storageRoutes = getStorage('routesAsync')
  if (path === '/login') {
    next()
  } else {
    if (store.state.app.user == null && storageRoutes == null) {
      next({ path: '/login' })
    } else if (store.state.app.user == null && storageRoutes != null) {
      addRoute()
      next({ path: '/' })
    } else {
      next()
    }
  }
})

// 添加动态路由
export function addRoute () {
  // 先保存 routesAsync,user 至 vuex
  store.dispatch('setMenuList', generaRouters([], getStorage('routesAsync')))
  store.dispatch('setUser', getStorage('user'))
  router.addRoutes(store.state.sidebar.menuList)
  router.addRoutes(routesError)
}

// 生成动态路由
function generaRouters (routesAsync, list) {
  list.forEach((item) => {
    let routerItem = {}
    routerItem.path = (item.children && item.children.length > 0) ? ('/' + item.code) : item.code
    routerItem.name = item.code
    routerItem.meta = { title: item.name, icon: item.icon || '' }
    routerItem.component = resolve => require([`@/views/${(!(item.children && item.children.length > 0) ? routerItem.name : 'layout')}/Index.vue`], resolve)
    if (item.children && item.children.length > 0) {
      routerItem.children = generaRouters([], item.children)
    }
    routesAsync.push(routerItem)
  })
  return routesAsync
}

export default router
